<?php

namespace services\patient;

use common\helpers\RedisHelper;
use common\models\baibai\Model;
use common\models\base\Project;
use common\models\clinic\Treatment;
use common\models\oss\Attachment;
use services\baibai\ConfigService;
use services\baibai\DataMigrateService;
use Yii;
use common\components\Service;
use common\helpers\ImageHelper;
use common\helpers\OssHelper;
use common\helpers\CommonHelper;
use common\models\patient\ClinicImg;
use common\models\oss\ImgRecord;
use api\modules\v1\forms\patient\ClinicImgForm;
use yii\db\Expression;
use yii\web\HttpException;

/**
 * Class ClinicImgService
 * @package services\patient
 */
class ClinicImgService extends Service
{
    protected $baibai_img_url = 'https://img.baibaiguanjia.com/';

    /**
     * 根据ID查找信息
     *
     * @param int $id
     * @return ClinicImg|null
     */
    public function findById(int $id = 0): ?ClinicImg
    {
        return ClinicImg::find()->where(['id' => $id])->one();
    }

    /**
     * 查找信息
     *
     * @param array $condition
     * @return ClinicImg|null
     */
    public function findInfo(array $condition = []): ?ClinicImg
    {
        $query = ClinicImg::find();

//        isset($condition['patient_user_id']) && $query->andWhere(['patient_user_id' => $condition['patient_user_id']]);

        return $query->one();
    }

    /**
     * 查找列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = ClinicImg::find();

        // select
        isset($condition['select']) && $query->select($condition['select']);

        // condition
        isset($condition['id']) && $query->andWhere(['id' => $condition['id']]);
        isset($condition['project_id']) && $query->andWhere(['project_id' => $condition['project_id']]);
        isset($condition['patient_card_id']) && $query->andWhere(['patient_card_id' => $condition['patient_card_id']]);
        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        // indexBy
        isset($condition['indexBy']) && $query->indexBy($condition['indexBy']);

        return $query->asArray()->all();
    }

    /**
     * 患者治疗图片列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getListPage(array $params = [], int $page = 0, int $pageSize = 0)
    {
        $query = ClinicImg::find()->select(['*'])
            ->where([
                'project_id' => $params['project_id'],
                'patient_card_id' => $params['patient_card_id'],
                'status' => ClinicImg::STATUS_ENABLE
            ]);

        // 部位
        if (isset($params['body_parts_id']) && $params['body_parts_id']) {
            $query->andWhere(['body_parts_id' => explode(',', $params['body_parts_id'])]);
        }

        // 图片日期
        if (isset($params['img_date']) && $params['img_date']) {
            $imgDateCondition = ['or'];
            foreach ($params['img_date'] as $row) {
                $imgDateCondition[] = ['=', 'img_date', $row];
            }
            $query->andWhere($imgDateCondition);
        }

        // 排序
        if (isset($params['sort_created_at_type']) && $params['sort_created_at_type']) {
            if ($params['sort_created_at_type'] == 1) {
                $orderBy = ['img_date' => SORT_ASC];
            } elseif ($params['sort_created_at_type'] == 2) {
                $orderBy = ['img_date' => SORT_DESC];
            }
        } else {
            $orderBy = ['img_date' => SORT_DESC];
        }

        $orderBy['id'] = SORT_DESC;

        $query->orderBy($orderBy);

        // 总数
        $total = $query->count();

        // 分页
        if ($page && $pageSize) {
            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $list = $query->asArray()->all();

        return [
            'page' => (int)$page,
            'pageSize' => (int)$pageSize,
            'total' => (int)$total,
            'list' => $list,
        ];
    }

    /**
     * 患者治疗图片日期
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getListDate(array $params = [])
    {
        $query = ClinicImg::find()
            ->select([
                'img_date'
            ])
            ->where([
                'project_id' => $params['project_id'],
                'patient_card_id' => $params['patient_card_id'],
                'status' => ClinicImg::STATUS_ENABLE
            ])
            ->groupBy('img_date')
            ->orderBy(['img_date' => SORT_DESC]);

        // 部位
        if (isset($params['body_parts_id']) && $params['body_parts_id']) {
            $query->andWhere(['body_parts_id' => explode(',', $params['body_parts_id'])]);
        }

        return $query->asArray()->all();
    }

    /**
     * 格式化列表数据
     *
     * @param array $data
     * @param int $type
     * @return array
     */
    public function getListPageFormat(array $data, int $projectId = 0)
    {
        $list = [];
        // 图片下载记录
        $ossImgRecord = Yii::$app->services->ossImgRecord->findList([
            'img_name' => array_column($data, 'img_url'),
            'indexBy' => 'img_name',
        ]);

        // 图片记录
        $insertData = [];
        $updateData = [];

        // 更新图片ID
        $updateId = [];
        foreach ($data as $row) {
            $fileUrl = '';
            $fileThumbUrl = '';
            if ($row['img_url']) {
                if (isset($ossImgRecord[$row['img_url']]) && $ossImgRecord[$row['img_url']]['status'] == ImgRecord::STATUS_ENABLE) {// 已下载
                    $fileUrl = ImageHelper::getOssImageUrl($row['img_url'], $projectId);
                    $fileThumbUrl = ImageHelper::getOssImageUrl($row['thumb_img_url'], $projectId);
                } else {// 未下载
                    try {
                        $ossHelper = new OssHelper();
                        // 下载原图
                        $downInfo = $ossHelper->download($row['img_url'], $row['img_url'], $projectId);
                        $fileUrl = $downInfo['file_url'];
                        // 下载缩略图
                        $downInfo = $ossHelper->download($row['img_url'], $row['thumb_img_url'], $projectId, 1);
                        $fileThumbUrl = $downInfo['file_url'];
                    } catch (\Exception $e) {
                        continue;
                    }

                    if (isset($ossImgRecord[$row['img_url']])) {
                        $updateData[] = $ossImgRecord[$row['img_url']]['id'];
                    } else {
                        $insertData[] = [
                            'img_name' => $row['img_url'],
                            'source_type' => ImgRecord::SOURCE_TYPE_PC,
                            'status' => ImgRecord::STATUS_ENABLE,
                            'created_at' => Yii::$app->params['time'],
                        ];
                    }
                }
            }

            $updateId[] = $row['id'];

            $item = [
                'id' => $row['id'],
                'project_id' => $row['project_id'],
                'patient_card_id' => $row['patient_card_id'],
                'img_url' => $fileUrl,
                'img_thumb_url' => $fileThumbUrl,
                'body_parts_id' => $row['body_parts_id'],
                'body_parts_name' => $row['body_parts_name'],
                'created_at_str' => $row['img_date'],
                //'created_at_str' => $row['created_at'] ? date('Y-m-d', $row['created_at']) : '',
            ];

            $list[] = $item;
        }

        // 新增下载记录
        if (!empty($insertData)) {
            Yii::$app->db->createCommand()->batchInsert(
                ImgRecord::tableName(),
                ['img_name', 'source_type', 'status', 'created_at'],
                $insertData
            )->execute();
        }

        // 更新下载记录
        if (!empty($updateData)) {
            ImgRecord::updateAll([
                'status' => ImgRecord::STATUS_ENABLE,
                'updated_at' => Yii::$app->params['time'],
            ], ['id' => $updateData]);
        }

        // 更新访问时间
        if (!empty($updateId)) {
            ClinicImg::updateAll(['updated_at' => Yii::$app->params['time']], ['id' => $updateId]);
        }

        return $list;
    }

    /**
     * 编辑图片部位
     *
     * @param ClinicImgForm $model
     * @return array|mixed
     */
    public function editBodyParts(ClinicImgForm $model)
    {
        try {
            $bodyPartsList = $model->getBodyPartsList();

            foreach ($model->getClinicImgList() as $row) {
                $attr = [
                    'body_parts_id' => $row['body_parts_id'],
                    'body_parts_name' => $bodyPartsList[$row['body_parts_id']]['body_parts_name'] ?? '',
                ];
                ClinicImg::updateAll($attr, ['id' => $row['id']]);
            }

            return ['patient_card_id' => $model->patient_card_id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 删除图片部位
     *
     * @param ClinicImgForm $model
     * @return array|mixed
     */
    public function delete(ClinicImgForm $model, int $projectId)
    {
        try {
            $clinicImgList = $model->getClinicImgByIdList();

            // 1.删除治疗图片
            ClinicImg::updateAll(['status' => ClinicImg::STATUS_DELETE], ['id' => array_column($clinicImgList, 'id')]);

            // 2.删除本地图片
            $project = RedisHelper::getProjectById($projectId);
            foreach ($clinicImgList as $row) {
                $saveFile = "{$row['img_url']}";
                if ($project) {
                    $saveFile = "{$project['name_sx']}/{$saveFile}";
                }

                // 完整路径
                $saveFileName = Yii::$app->params['upload_dir'] . "/{$saveFile}";
                @unlink($saveFileName);
            }

            return ['ids' => $model->ids];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 执行本地图片上传到oss
     * @return bool
     * @throws HttpException
     * @throws \OSS\Core\OssException
     * @author chenyuebin
     */
    public function addClinicImg()
    {
        $redis = Yii::$app->redis;
        // 获取项目信息
        $project = Project::find()
            ->select([
                'id',
                'name_sx'
            ])
            ->where(['status' => Project::STATUS_ENABLE])
            ->asArray()
            ->all();
        foreach ($project as $value) {// 循环各项目
            if (!$value['name_sx']) {// 没有项目简称则忽略
                continue;
            }
            if (!is_dir('/data/baiyou_origin_img/' . $value['name_sx'])) {// 找不到对应目标文件夹，则忽略
                continue;
            }
            if (!file_exists('/data/baiyou_origin_img/' . $value['name_sx'] . '/ready.txt')) {
                echo date("Y-m-d H:i:s") . "==>".$value['name_sx'] . ":sorry! ready.txt is undefined!\n";
                continue;
            } else {
                unlink('/data/baiyou_origin_img/' . $value['name_sx'] . '/ready.txt');
            }

            $redis->del('oss_' . $value['id']);// 清空redis以前数据
            $imgs = ClinicImg::find()
                ->select(['origin_img_url'])
                ->where([
                    'and',
                    ['project_id' => $value['id']],
                    ['status' => ClinicImg::STATUS_ENABLE]
                ])
                ->asArray()
                ->all();
            $imgList = '';
            foreach ($imgs as $v) {
                $imgList .= $v['origin_img_url'] . ',';
            }
            $redis->set('oss_' . $value['id'], $imgList);
            $redisImg = $redis->get('oss_' . $value['id']);
            $redisImgArr = array_filter(explode(',', $redisImg));


            $dir = scandir('/data/baiyou_origin_img/' . $value['name_sx'] . '/');
            foreach ($dir as $val) {// 循环上传各项目文件
                if ($val == '.' || $val == '..') {
                    continue;
                }
                if (in_array($val, $redisImgArr)) {
                    echo date("Y-m-d H:i:s") . "==>IMG: 【/data/baiyou_origin_img/" . $value['name_sx'] . "/" . $val . "】  is already exist,faineancy!\n";
                    file_put_contents('/data/wwwlogs/oss_upload.txt', date("Y-m-d H:i:s") . '==>' . $value['name_sx'] . '==>图片：' . "【/data/baiyou_origin_img/" . $value['name_sx'] . "/" . $val . "已经存在，忽略本图\n", FILE_APPEND);
                    unlink('/data/baiyou_origin_img/' . $value['name_sx'] . '/' . $val);// 删除已经成功上传的本地文件
                    continue;
                }
                // 获取图片基本信息
                if (filesize('/data/baiyou_origin_img/' . $value['name_sx'] . '/' . $val) <= 0) {
                    echo date("Y-m-d H:i:s") . "==>IMG: 【/data/baiyou_origin_img/" . $value['name_sx'] . "/" . $val . "】  error,please check!\n";
                    file_put_contents('/data/wwwlogs/oss_upload.txt', date("Y-m-d H:i:s") . '==>' . $value['name_sx'] . '==>图片：' . "【/data/baiyou_origin_img/" . $value['name_sx'] . "/" . $val . "图片存在问题，忽略本图\n", FILE_APPEND);
                    continue;
                }
                $imageInfo = getimagesize('/data/baiyou_origin_img/' . $value['name_sx'] . '/' . $val);
                $width = $imageInfo[0];// 宽
                $height = $imageInfo[1];// 高
                $upload_type = 'images';// 上传类型
                $specific_type = $imageInfo['mime'];// 类别
                $size = filesize('/data/baiyou_origin_img/' . $value['name_sx'] . '/' . $val);// 图片大小


                // 解析原始文件名
                $all_path_name = explode('-', $val);
                if (count($all_path_name) <= 1) {
                    continue;
                }
                $oss_first_path = $all_path_name[0];// 根目录
                $oss_sec_path = substr($all_path_name[1], 0, 6);// 下级目录
                $file_date = substr($all_path_name[1], 0, 8);// 根据文件名获取文件日期【Ymd】

                $name = explode('.', $val)[0];// 获取原始文件的名称
                $extension = explode('.', $val)[1];// 获取文件的后缀名
                $fileName = ImageHelper::createFileName($extension);// 重新生成文件名称
                $oss_path = $value['name_sx'] . '/' . $oss_first_path . '/' . $oss_sec_path . '/' . $fileName;// 最终存入oss的文件路径

                // 执行上传到oss
                $oss = new OssHelper();
                // 上传原图
                $uploadRet = $oss->upload('/data/baiyou_origin_img/' . $value['name_sx'] . '/' . $val, $oss_path);
                // 执行成功后录入数据
                if (isset($uploadRet['info']['http_code']) && $uploadRet['info']['http_code'] == 200) {
                    $upload_ip = $uploadRet['info']['primary_ip'];// 上传ip
                    $md5 = $uploadRet['content-md5'];// md5校验码

                    try {
                        $transaction = Yii::$app->db->beginTransaction();

                        // 患者治疗图片表录入
                        $clinicImg = new ClinicImg();
                        $clinicImg->project_id = $value['id'];
                        $clinicImg->created_at = time();
                        $clinicImg->updated_at = time();
                        $clinicImg->body_parts_id = 0;
                        $clinicImg->body_parts_name = '';
                        $clinicImg->img_date = date("Y-m-d", strtotime($file_date));
                        $clinicImg->origin_img_url = $val;
                        $clinicImg->img_url = $oss_first_path . '/' . $oss_sec_path . '/' . explode('.', $fileName)[0] . '.' . $extension;
                        $clinicImg->thumb_img_url = $oss_first_path . '/' . $oss_sec_path . '/' . explode('.', $fileName)[0] . '_min' . '.' . $extension;
                        $clinicImg->patient_card_id = $oss_first_path;
                        $clinicImg->save();

                        // OSS_文件管理表录入
                        $ossAttach = new Attachment();
                        $ossAttach->updated_at = time();
                        $ossAttach->created_at = time();
                        $ossAttach->project_id = $value['id'];
                        $ossAttach->name = $name;
                        $ossAttach->year = date("Y", strtotime($file_date));
                        $ossAttach->month = date("m", strtotime($file_date));
                        $ossAttach->day = date("d", strtotime($file_date));
                        $ossAttach->base_url = $oss_first_path . '/' . $oss_sec_path . '/' . $fileName;
                        $ossAttach->extension = $extension;
                        $ossAttach->height = $height;
                        $ossAttach->width = $width;
                        $ossAttach->md5 = $md5;
                        $ossAttach->path = $oss_first_path . '/' . $oss_sec_path . '/' . explode('.', $fileName)[0];
                        $ossAttach->size = $size;
                        $ossAttach->upload_ip = $upload_ip;
                        $ossAttach->upload_type = $upload_type;
                        $ossAttach->specific_type = $specific_type;
                        $ossAttach->save();

                        $transaction->commit();
                    } catch (\Exception $exception) {
                        $transaction->rollBack();
                        throw new HttpException(422, $exception->getMessage());
                    }

                    unlink('/data/baiyou_origin_img/' . $value['name_sx'] . '/' . $val);// 删除成功上传的本地文件
                }
            }
            $redis->del('oss_' . $value['id']);// 清空redis以前数据
        }
        return true;
    }

    /**
     * 修复图片缺失的上传日期
     * @author chenyuebin
     */
    public function ClinicImgRepair()
    {
        $list = ClinicImg::find()
            ->select(['origin_img_url', 'id'])
            ->asArray()
            ->all();
        foreach ($list as $value) {
            $date = $value['origin_img_url'];// 06707107-201809161800023075021.jpg
            $date = explode('-', $date);
            $dates = substr($date[1], 0, 8);// 根据文件名获取文件日期【Ymd】
            ClinicImg::updateAll(['img_date' => date("Y-m-d", strtotime($dates))], ['id' => $value['id']]);
        }
    }

    // ================================白白管家相关图片上传====================

    /**
     * 白白管家治疗图片上传
     *
     * @throws HttpException
     * @throws \OSS\Core\OssException
     * @author chenyuebin
     */
    public function baibaiImgUpload()
    {
        Model::setTableName('bm_patient_attach_info');
        $patient_attach_id = file_get_contents('/data/baiyou_origin_img/bb/read_id.txt');
        $list = Model::find()
            ->alias('pai')
            ->leftJoin('bm_patient_attach as pa', 'pai.patient_attach_id=pa.id')
            ->leftJoin('bm_patient as p', 'pa.patient_id=p.id')
            ->select(['pai.*', 'p.treat_no', 'p.id as p_id'])
            ->orderBy('pai.id asc')
            ->where(['>', 'pai.id', $patient_attach_id])
            ->asArray()
            ->all();

        foreach ($list as $val) {
            $imageInfo = getimagesize($this->baibai_img_url . $val['file_path']);
            $width = $imageInfo[0];// 宽
            $height = $imageInfo[1];// 高
            $upload_type = 'images';// 上传类型
            $specific_type = $imageInfo['mime'];// 类别
            $file = file_get_contents($this->baibai_img_url . $val['file_path']);
            /*var_dump(strlen($file));return;
            $size = $this->remote_filesize($this->baibai_img_url . $val['file_path'])['size'];// 图片大小*/
            $size = strlen($file);// 图片大小

            // 解析原始文件名
            $all_path_name = explode('/', $val['file_path']);
            if (count($all_path_name) <= 1) {
                continue;
            }
            $oss_first_path = DataMigrateService::havePatient($val['p_id']);// 根目录
            $oss_sec_path = $all_path_name[2];// 下级目录
            $file_date = $all_path_name[2] . $all_path_name[3];// 根据文件名获取文件日期【Ymd】
            $file_dates = date("Ym", strtotime($all_path_name[2] . $all_path_name[3]));// 根据文件名获取文件日期【Ymd】

            $name = explode('.', $all_path_name[4])[0];// 获取原始文件的名称
            $extension = explode('.', $all_path_name[4])[1];// 获取文件的后缀名
            $fileName = ImageHelper::createFileName($extension);// 重新生成文件名称
            $oss_path = 'bb/' . $oss_first_path . '/' . $file_dates . '/' . $fileName;// 最终存入oss的文件路径

            // 执行上传到oss
            $oss = new OssHelper();
            // 上传原图
            file_put_contents('/data/baiyou_origin_img/bb/temp.' . $extension, file_get_contents($this->baibai_img_url . $val['file_path']));
            /*echo '/data/baiyou_origin_img/bb/temp.' . $extension . "\n";
            echo $oss_path . "\n";*/
            $uploadRet = $oss->upload('/data/baiyou_origin_img/bb/temp.' . $extension, $oss_path);

            // 执行成功后录入数据
            if (isset($uploadRet['info']['http_code']) && $uploadRet['info']['http_code'] == 200) {
                $upload_ip = $uploadRet['info']['primary_ip'];// 上传ip
                $md5 = $uploadRet['content-md5'];// md5校验码

                try {
                    $transaction = Yii::$app->db->beginTransaction();

                    // 患者治疗图片表录入
                    $clinicImg = new ClinicImg();
                    $clinicImg->project_id = 13;
                    $clinicImg->created_at = time();
                    $clinicImg->updated_at = time();
                    $clinicImg->body_parts_id = ConfigService::LARGE_BODY_PARTS[$val['body_large_id']];
                    $clinicImg->body_parts_name = $val['body_large_name'];
                    $clinicImg->img_date = date("Y-m-d", strtotime($file_date));
                    $clinicImg->origin_img_url = $val['file_path'];
                    $clinicImg->img_url = $oss_first_path . '/' . $file_dates . '/' . explode('.', $fileName)[0] . '.' . $extension;
                    $clinicImg->thumb_img_url = $oss_first_path . '/' . $file_dates . '/' . explode('.', $fileName)[0] . '_min' . '.' . $extension;
                    $clinicImg->patient_card_id = (string)$oss_first_path;

                    if (!$clinicImg->save()) {
                        throw new \Exception(json_encode($clinicImg->getErrors()), 400);
                    }

                    // OSS_文件管理表录入
                    $ossAttach = new Attachment();
                    $ossAttach->updated_at = time();
                    $ossAttach->created_at = time();
                    $ossAttach->project_id = 13;
                    $ossAttach->name = $name;
                    $ossAttach->year = date("Y", strtotime($file_date));
                    $ossAttach->month = date("m", strtotime($file_date));
                    $ossAttach->day = date("d", strtotime($file_date));
                    $ossAttach->base_url = $oss_first_path . '/' . $file_dates . '/' . $fileName;
                    $ossAttach->extension = $extension;
                    $ossAttach->height = $height;
                    $ossAttach->width = $width;
                    $ossAttach->md5 = $md5;
                    $ossAttach->path = $oss_first_path . '/' . $file_dates . '/' . explode('.', $fileName)[0];
                    $ossAttach->size = $size;
                    $ossAttach->upload_ip = $upload_ip;
                    $ossAttach->upload_type = $upload_type;
                    $ossAttach->specific_type = $specific_type;
                    if (!$ossAttach->save()) {
                        throw new \Exception(json_encode($ossAttach->getErrors()), 400);
                    }
                    $transaction->commit();
                } catch (\Exception $exception) {
                    $transaction->rollBack();
                    throw new HttpException(422, $exception->getMessage());
                }
            }
            file_put_contents('/data/baiyou_origin_img/bb/read_id.txt', $val['id']);
            clearstatcache();
            sleep(1);
        }

    }

    /**
     * 白白管家患者签名图片上传
     *
     * @throws HttpException
     * @throws \OSS\Core\OssException
     * @author chenyuebin
     */
    public function baibaiSignImgUpload()
    {
        Model::setTableName('bm_treat');
        $patient_attach_id = file_get_contents('/data/baiyou_origin_img/bb/read_treat_id.txt');
        $list = Model::find()
            ->select(['patient_id', 'id', 'finished_at', 'sign'])
            ->orderBy('id asc')
            ->where(['>', 'id', $patient_attach_id])
            ->andWhere(['!=', 'sign', ''])
            ->asArray()
            ->all();
        foreach ($list as $val) {
            echo $val['sign'] . "\n";
            $val['sign'] = trim($val['sign'], '"');
            echo $val['sign'] . "\n";
            if ($val['sign'] == '') {
                continue;
            }

            // 解析原始文件名
            $all_path_name = explode('/', $val['sign']);
            if (count($all_path_name) <= 1) {
                continue;
            }
            $oss_first_path = DataMigrateService::havePatient($val['patient_id']);// 根目录
            $oss_sec_path = $all_path_name[2];// 下级目录
            $file_date = $all_path_name[2] . $all_path_name[3];// 根据文件名获取文件日期【Ymd】
            $file_dates = date("Ym", strtotime($all_path_name[2] . $all_path_name[3]));// 根据文件名获取文件日期【Ymd】

            $extension = explode('.', $all_path_name[4])[1];// 获取文件的后缀名
            $fileName = ImageHelper::createFileName($extension);// 重新生成文件名称
            $oss_path = 'bb/' . $oss_first_path . '/' . $file_dates . '/' . $fileName;// 最终存入oss的文件路径

            // 执行上传到oss
            $oss = new OssHelper();
            // 上传原图
            file_put_contents('/data/baiyou_origin_img/bb/temp_treat.' . $extension, file_get_contents($this->baibai_img_url . $val['sign']));
            $uploadRet = $oss->upload('/data/baiyou_origin_img/bb/temp_treat.' . $extension, $oss_path);

            // 执行成功后录入数据
            if (isset($uploadRet['info']['http_code']) && $uploadRet['info']['http_code'] == 200) {
                echo DataMigrateService::havePatient($val['patient_id']) . '===>' . $val['finished_at'] . "\n";
                try {
                    // OSS_文件管理表录入
                    $ret = Treatment::updateAll(
                        ['patient_signature' => $oss_first_path . '/' . $file_dates . '/' . explode('.', $fileName)[0] . '.' . $extension],
                        [
                            'patient_card_id' => DataMigrateService::havePatient($val['patient_id']),
                            'clinic_time' => $val['finished_at']
                        ]
                    );
                } catch (\Exception $exception) {
                    throw new HttpException(422, $exception->getMessage());
                }
            }
            file_put_contents('/data/baiyou_origin_img/bb/read_treat_id.txt', $val['id']);
            clearstatcache();
            sleep(1);
        }
    }


    public function remote_filesize($url, $type = 'curl', $isGetFilesize = true)
    {
        // 若需要获取图片体积大小则默认使用 fread 方式
        $type = $isGetFilesize ? 'fread' : $type;

        if ($type == 'fread') {
            // 或者使用 socket 二进制方式读取, 需要获取图片体积大小最好使用此方法
            $handle = fopen($url, 'rb');

            if (!$handle) return false;

            // 只取头部固定长度168字节数据
            $dataBlock = fread($handle, 168);
        } else {
            // 据说 CURL 能缓存DNS 效率比 socket 高
            $ch = curl_init($url);
            // 超时设置
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            // 取前面 168 个字符 通过四张测试图读取宽高结果都没有问题,若获取不到数据可适当加大数值
            curl_setopt($ch, CURLOPT_RANGE, '0-167');
            // 跟踪301跳转
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            // 返回结果
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $dataBlock = curl_exec($ch);

            curl_close($ch);

            if (!$dataBlock) return false;
        }

        // 将读取的图片信息转化为图片路径并获取图片信息,经测试,这里的转化设置 jpeg 对获取png,gif的信息没有影响,无须分别设置
        // 有些图片虽然可以在浏览器查看但实际已被损坏可能无法解析信息
        $size = getimagesize('data://image/jpeg;base64,' . base64_encode($dataBlock));
        if (empty($size)) {
            return false;
        }

        $result['width'] = $size[0];
        $result['height'] = $size[1];

        // 是否获取图片体积大小
        if ($isGetFilesize) {
            // 获取文件数据流信息
            $meta = stream_get_meta_data($handle);
            // nginx 的信息保存在 headers 里，apache 则直接在 wrapper_data
            $dataInfo = isset($meta['wrapper_data']['headers']) ? $meta['wrapper_data']['headers'] : $meta['wrapper_data'];

            foreach ($dataInfo as $va) {
                if (preg_match('/length/iU', $va)) {
                    $ts = explode(':', $va);
                    $result['size'] = trim(array_pop($ts));
                    break;
                }
            }
        }

        if ($type == 'fread') fclose($handle);

        return $result;
    }

    /**
     * @Notes: 恢复patient_clinic_img数据【针对定时删除本地服务器图片-清理15天前的数据的修复脚本】
     *
     * 此脚本将会查询 by_oss_attachment 表数据
     * 此脚本将会向 by_patient_clinic_img 表插入数据
     *
     * @Interface repairClinicImg
     * @throws \yii\db\Exception
     * @author: chenyuebin
     * @Time: 2022/5/4 0004   15:09
     */
    public function repairClinicImg()
    {
        $insertNum = 0;
        $time = strtotime(date('Ymd', strtotime("-15 day")));
        $patientAttachmentQuery = Attachment::find()
            ->select('project_id,created_at,updated_at,year,month,day,name,base_url,extension')
            ->where(['<=', 'updated_at', $time]);

        foreach ($patientAttachmentQuery->batch(500) as $tmpData) {
            $insertData = [];
            foreach ($tmpData as $value) {
                $urlArr = explode('/', $value['base_url']);
                $urlPathArr = explode('.', $value['base_url']);
                $insertData[] = [
                    'project_id' => $value['project_id'],
                    'created_at' => $value['created_at'],
                    'updated_at' => $value['updated_at'],
                    'body_parts_id' => 0,
                    'body_parts_name' => '',
                    'img_date' => $value['year'] . '-' . $value['month'] . '-' . $value['day'],
                    'origin_img_url' => $value['name'] . '.' . $value['extension'],
                    'img_url' => $urlPathArr[0] . '.' . $value['extension'],
                    'thumb_img_url' => $urlPathArr[0] . '_min' . '.' . $value['extension'],
                    'patient_card_id' => $urlArr[0],
                ];
            }
            if ($insertData) {
                $ret = Yii::$app->db->createCommand()
                    ->batchInsert(ClinicImg::tableName(), [
                        'project_id',
                        'created_at',
                        'updated_at',
                        'body_parts_id',
                        'body_parts_name',
                        'img_date',
                        'origin_img_url',
                        'img_url',
                        'thumb_img_url',
                        'patient_card_id'
                    ], $insertData)->execute();

                $insertNum += $ret;
            }
        }
        print_r('成功恢复 【' . $insertNum . '】 条数据');
    }

    /**
     * 删除oss线上图片
     * @return void
     */
    public function deleteOssImage($params)
    {
        // 查找指定项目诊疗号图片
        $project_id = $params['project_id'];
        $patient_card_id = $params['patient_card_id'];

        $clinicArray = ClinicImg::find()
            ->select("id,img_url")
            ->where([
                "patient_card_id" => $patient_card_id,
                "project_id" => $project_id
            ])
            ->asArray()
            ->all();
        $idsArray = array_column($clinicArray,"id");
        $imgUrl = array_column($clinicArray,"img_url");

        # 1.删除数据库图片信息 3.删除数据库图片下载记录 4.删除服务器图片
        $model = new ClinicImgForm();
        $model->setScenario('delete');

        Yii::$app->params['test-delete-img'] = true;
        $model->attributes = [
            'project_id' => $project_id,
            'ids' => implode(',',$idsArray),
        ];
        if (!$model->validate()) {
            // 返回数据验证失败
            return CommonHelper::api(422, $this->getError($model));
        }
        $this->delete($model, $project_id);

        # 2. 删除线上oss图片
        // 获取线上图片地址
        $objectArray = [];
        $project = RedisHelper::getProjectById($project_id);
        if ($project) {
            $projectName = $project['name_sx'];
            foreach ($imgUrl as $item) {
                $objectArray[] = $projectName."/".$item;
            }
        }
        // 执行删除oss图片
        $oss = new OssHelper();
        $uploadRet = $oss->deleteImage($objectArray);
    }
}
